const { readFile, writeFile } = require('../model/userModel');

// 验证用户名是否符合要求
const validateUsername = username => /^\w{6}$/.test(username);

// 验证密码是否符合要求
const validatePassword = password => /^\d{6}$/.test(password);

// 处理注册请求
module.exports.handleRegister = (req, res) => {
    const { username, password } = req.query;
    if (!validateUsername(username)) return res.send({ message: '注册失败!用户名不符合要求!', status: 204 });
    if (!validatePassword(password)) return res.send({ message: '注册失败!密码不符合要求!', status: 204 });

    const tempUser = readFile('data.json');
    if (tempUser.some(item => item.username === username)) return res.send({ message: '注册失败!用户名已存在!', status: 204 });

    tempUser.push({ username, password });
    writeFile('data.json', tempUser);

    res.send({ message: '注册成功!', status: 200 });
};

// 处理登录请求
module.exports.handleLogin = (req, res) => {
    const { username, password } = req.query;
    if (!validateUsername(username)) return res.send({ message: '用户名不符合要求!', status: 204 });
    if (!validatePassword(password)) return res.send({ message: '密码不符合要求!', status: 204 });

    const tempUser = readFile('data.json');
    const user = tempUser.find(item => item.username === username);
    if (!user) return res.json({ message: '用户名不存在', status: 204 });
    if (user.password !== password) return res.json({ message: '密码错误', status: 204 });

    res.send({ message: '登录成功!', status: 200 });
};

// 处理更新密码请求
module.exports.handleUpdatePassword = (req, res) => {
    const { username, oldpassword, newpassword, repeatpassword } = req.query;

    if (!checkToken(req)) return res.send({ message: '未登录!', status: 401 });

    const tempUser = readFile('data.json');
    const user = tempUser.find(item => item.username === username);
    if (!user) return res.send({ message: '用户名不存在!', status: 204 });
    if (user.password !== oldpassword) return res.send({ message: '旧密码错误!', status: 204 });
    if (newpassword !== repeatpassword) return res.send({ message: '新密码和重复密码不一致!', status: 204 });

    user.password = newpassword;
    writeFile('data.json', tempUser);

    res.send({ message: '密码更新成功!', status: 200 });
};